package com.xx.pmis.web.actions;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.xx.pmis.model.Book;
import com.xx.pmis.model.Shop;
import com.xx.pmis.services.BookService;
import com.xx.pmis.services.ShopService;
import com.xx.pmis.web.forms.BookForm;
import com.xx.pmis.web.util.AccountUtil;
import com.xx.pmis.web.util.CurrentDate;
import com.xx.pmis.web.util.Rand;

/**
 * @class 图书Action类 <br>
 * 
 * @editor 石星星 @Date 2011-9-21 下午03:17:42 <br>
 * @version jdk_1.5.0
 */
public class BookAction extends PMISBaseAction {
	private static final Log log = LogFactory.getLog(BookAction.class);

	BookService bookService = getPMISServices().getBookService();
	ShopService shopService = getPMISServices().getShopService();

	AccountUtil accountUtil = new AccountUtil();

	// 查询所有图书
	public ActionForward listBook(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		List<Book> all = null;
		try {
			all = bookService.getAllBookByCondition(" order by bookDate desc");
		} catch (Exception e) {
			String errorPage = "【物资管理/图书】查询【图书】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("bookList", all);
		return mapping.findForward("listBook");
	}

	// 新增
	public ActionForward addBook(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		List<?> shopList = null;
		try {
			shopList = shopService.getAllShopByShopType("1");
		} catch (Exception e) {
			String errorPage = "【物资管理/图书/新增】查询【商店】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("shopList", shopList);
		request.setAttribute("bookDate", CurrentDate.currentDate());
		request.setAttribute("position", "图书/新增");
		return mapping.findForward("addBook");
	}

	// 新增，处理方法
	public ActionForward addBook_Do(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		BookForm f = (BookForm) form;

		String bookName = f.getBookName(); // 图书名称
		String author = f.getAuthor(); // 作者
		String readState = f.getReadState(); // 想读 0，在读 1，已读
		String bookState = f.getBookState(); // 在家0，丢失 1，借出 2
		String bookDate = f.getBookDate(); // 购买日期，结算时作为流水账的记账日期
		String bookPrice = f.getBookPrice(); // 定价
		String bookExpenses = f.getBookExpenses(); // 费用，购买的费用，用于计算折扣
		String bookDesc = f.getBookDesc(); // 描述
		String shopID = f.getShopID();

		Book book = new Book();
		book.setBookID(CurrentDate.currentYear() + Rand.getRand());
		book.setBookName(bookName);
		book.setAuthor(author);
		book.setReadState(readState);
		book.setBookState(bookState);
		book.setBookDate(bookDate);
		book.setBookPrice(bookPrice);
		book.setBookExpenses(accountUtil.if1ZeroTo2Zero(bookExpenses));
		// 计算折扣
		double discount = (Double.parseDouble(bookPrice) - Double.parseDouble(bookExpenses))
				/ Double.parseDouble(bookPrice);
		book.setDiscount(new DecimalFormat("####.#").format(discount));
		book.setBookDesc(bookDesc);
		book.setBookPay("1");

		book.setShopID(shopID);
		try {
			bookService.saveOrUpdateBook(book);
		} catch (Exception e) {
			String errorPage = "【物资管理/图书/新增】保存或更新【图书】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		listBookByPage(mapping, form, request, response);
		return mapping.findForward("listBook");
	}

	// 编辑
	public ActionForward editBook(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String bookID = request.getParameter("bookID");
		String pageNum = request.getParameter("pageNum");
		List<Shop> shopList = null;
		try {
			shopList = shopService.getAllShop();
		} catch (Exception e) {
			String errorPage = "【物资管理/图书/编辑】查询【商店】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("shopList", shopList);
		Book book = null;
		try {
			book = bookService.getBookByBookID(bookID);
		} catch (Exception e) {
			String errorPage = "【物资管理/图书/编辑】根据【图书ID】查询该【图书】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		
		Shop shop = null;
		try {
			shop = shopService.getShopByShopID(book.getShopID());
		} catch (Exception e) {
			String errorPage = "【物资管理/图书/编辑】根据ID查询该【商店】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		request.setAttribute("pageNum", pageNum);
		request.setAttribute("book", book);
		request.setAttribute("shopName", shop.getShopName());
		request.setAttribute("position", "图书/编辑");
		return mapping.findForward("editBook");
	}

	// 编辑，处理方法
	public ActionForward editBook_Do(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String pageNum = request.getParameter("pageNum");
		log.info("------------------------begin-------------------------------");
		log.info("pageNum:" + pageNum);
		log.info("------------------------end---------------------------------");
		BookForm f = (BookForm) form;
		String bookID = f.getBookID();
		String bookName = f.getBookName(); // 图书名称
		String author = f.getAuthor(); // 作者
		String readState = f.getReadState(); // 想读 0，在读 1，已读
		String bookState = f.getBookState(); // 在家0，丢失 1，借出 2
		String bookDate = f.getBookDate(); // 购买日期，结算时作为流水账的记账日期
		String bookPrice = f.getBookPrice(); // 定价
		String bookExpenses = f.getBookExpenses(); // 费用，购买的费用，用于计算折扣
		String bookDesc = f.getBookDesc(); // 描述
		String shopID = f.getShopID();

		Book book = null;
		try {
			book = bookService.getBookByBookID(bookID);
		} catch (Exception e) {
			String errorPage = "【物资管理/图书/编辑】根据【图书ID】查询该【图书】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		book.setBookName(bookName);
		book.setAuthor(author);
		book.setReadState(readState);
		book.setBookState(bookState);
		book.setBookDate(bookDate);
		book.setBookPrice(bookPrice);
		book.setBookExpenses(accountUtil.if1ZeroTo2Zero(bookExpenses));
		// 计算折扣
		double discount = (Double.parseDouble(bookPrice) - Double.parseDouble(bookExpenses))
				/ Double.parseDouble(bookPrice);
		book.setDiscount(new DecimalFormat("####.#").format(discount));
		book.setBookDesc(bookDesc);

		book.setShopID(shopID);
		try {
			bookService.saveOrUpdateBook(book);
		} catch (Exception e) {
			String errorPage = "【物资管理/图书/编辑】保存或更新【图书】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		request.setAttribute("pageNum", pageNum);
		listBookByPage(mapping, form, request, response);
		return mapping.findForward("listBook");
	}

	// 删除
	public ActionForward delBook(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String pageNum = request.getParameter("pageNum");
		Book book = null;
		BookForm f = (BookForm) form;
		String[] ids = f.getIds();
		for (int i = 0; i < ids.length; i++) {
			try {
				book = bookService.getBookByBookID(ids[i]);
			} catch (Exception e) {
				String errorPage = "【物资管理/图书/删除】根据【图书ID】查询该【图书】异常！" + e.toString();
				log.info(errorPage);
				request.setAttribute("errorPage", errorPage);
				request.setAttribute("position", "出错了");
				return mapping.findForward("errorPage");
			}
			try {
				bookService.deleteBook(book);
			} catch (Exception e) {
				String errorPage = "【物资管理/图书/删除】删除【图书】异常！" + e.toString();
				log.info(errorPage);
				request.setAttribute("errorPage", errorPage);
				request.setAttribute("position", "出错了");
				return mapping.findForward("errorPage");
			}
		}
		request.setAttribute("pageNum", pageNum);
		listBookByPage(mapping, form, request, response);
		return mapping.findForward("listBook");
	}

	// 结算
	public ActionForward payBook(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String bookID = request.getParameter("bookID");
		String pageNum = request.getParameter("pageNum");
		Book book = new Book();
		try {
			book = bookService.getBookByBookID(bookID);
		} catch (Exception e) {
			String errorPage = "【物资管理/图书/结算】根据【图书ID】查询该【图书】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		// 生成记账凭证
		accountUtil.payExpenseToAccount(book.getBookDate(), "0030004", "1", book.getBookExpenses(), "购买", book
				.getBookName());
		// 更新结算状态，结算完成为"0"
		book.setBookPay("0");
		try {
			bookService.saveOrUpdateBook(book);
		} catch (Exception e) {
			String errorPage = "【物资管理/图书/新增】保存或更新【图书】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		request.setAttribute("pageNum", pageNum);
		listBookByPage(mapping, form, request, response);
		return mapping.findForward("listBook");
	}

	// 明细
	public ActionForward detailBook(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		String bookID = request.getParameter("bookID");

		Book book = null;
		try {
			book = bookService.getBookByBookID(bookID);
		} catch (Exception e) {
			String errorPage = "【物资管理/图书/明细】根据【图书ID】查询该【图书】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		request.setAttribute("book", book);
		request.setAttribute("position", "图书/明细");
		return mapping.findForward("detailBook");
	}

	// 分页显示
	public ActionForward listBookByPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		int PAGESIZE = 20;// 每页记录数
		int totalPage = 1;// 总页数

		// 查询总用户记录数
		int count = 0;
		try {
			count = bookService.getCountOfBookByCondition("");
		} catch (Exception e) {
			String errorPage = "【物资管理/图书】查询【图书】数目异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		request.setAttribute("count", count);
		if (count % PAGESIZE == 0) {
			totalPage = count / PAGESIZE;
		} else {
			totalPage = count / PAGESIZE + 1;
		}

		request.setAttribute("totalPage", totalPage);
		// 声明要翻的页
		String pageNum = "1";
		try {
			String thisPageNum = request.getParameter("pageNum");
			// 如果传了页码参数
			if (thisPageNum != null && thisPageNum.length() != 0) {
				pageNum = thisPageNum;
			}
		} catch (RuntimeException e) {
			log.info("" + e.toString());
		}
		log.info("page:" + pageNum);
		request.setAttribute("pageNum", pageNum);
		List<Book> bookList = null;
		List<Book> bookListTemp = new ArrayList<Book>();
		try {
			bookList = bookService.getAllBookByConditionByPage(" order by bookDate desc", Integer.parseInt(pageNum), PAGESIZE);
			for(Book book : bookList) {
				Shop shop = new Shop();
				try {
					shop = shopService.getShopByShopID(book.getShopID());
				} catch (Exception e) {
					String errorPage = "【物资管理/图书/分页显示】根据商店ID查询【商店】异常！" + e.toString();
					log.info(errorPage);
				}
				book.setShopName(shop.getShopName());
				bookListTemp.add(book);
			}
		} catch (Exception e) {
			String errorPage = "【物资管理/图书】查询【图书】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}
		List<Book> bookListTemp2 = new ArrayList<Book>();
		for (Book book : bookListTemp) {
			// 计算折扣
			double discount = (Double.parseDouble(book.getBookExpenses())) / Double.parseDouble(book.getBookPrice());
			String discountStr = new DecimalFormat("####.#").format(discount);
			if(discountStr.equals("1")) {
				discountStr = "0.10";
			} else if(discountStr.equals("0")) {
				discountStr = "0.0";
			}
			int discountInt = Integer.parseInt(discountStr.substring(2));
			String discountStrTemp = "";
			switch (discountInt) {
			case 10:
				discountStrTemp = "全价";
				break;
			case 9:
				discountStrTemp = "九折";
				break;
			case 8:
				discountStrTemp = "八折";
				break;
			case 7:
				discountStrTemp = "七折";
				break;
			case 6:
				discountStrTemp = "六折";
				break;
			case 5:
				discountStrTemp = "五折";
				break;
			case 4:
				discountStrTemp = "四折";
				break;
			case 3:
				discountStrTemp = "三折";
				break;
			case 2:
				discountStrTemp = "两折";
				break;
			case 1:
				discountStrTemp = "一折";
				break;
			case 0:
				discountStrTemp = "免费";
				break;
			}
			book.setDiscount(discountStrTemp);
			bookListTemp2.add(book);
		}
		request.setAttribute("bookList", bookListTemp2);
		request.setAttribute("PAGESIZE", PAGESIZE);
		// 如果要翻的这页是第一页
		if ("1".equals(pageNum)) {
			// 设置noUp为yes(界面上用此控制'首页'与'上一页'按钮失效)
			request.setAttribute("noUp", "yes");
		}

		// 如果要翻的这页是最后页
		if (totalPage == Integer.parseInt(pageNum)) {
			// 设置noDown为yes(界面上用此控制'下一页'与'尾页'按钮失效)
			request.setAttribute("noDown", "yes");
		}

		request.setAttribute("action", "book.do");
		request.setAttribute("position", "物资管理/图书");
		return mapping.findForward("listBook");
	}

	// 更改图书状态：已读、未读；在藏、丢失
	public ActionForward stateBook(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String bookID = request.getParameter("bookID");
		String state = request.getParameter("state");
		String pageNum = request.getParameter("pageNum");
		Book book = new Book();
		try {
			book = bookService.getBookByBookID(bookID);
		} catch (Exception e) {
			String errorPage = "【物资管理/图书/状态】根据【图书ID】查询该【图书】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		if ("yidu".equals(state)) {// 已读
			book.setReadState("1");
		} else if ("weidu".equals(state)) {// 未读
			book.setReadState("0");
		} else if ("zaicang".equals(state)) {// 在藏
			book.setBookState("0");
		} else if ("diushi".equals(state)) {// 丢失
			book.setBookState("1");
		} else {
			log.error("输入参数应为“yidu”，“weidu”，“zaicang”，“diushi”。");
		}

		try {
			bookService.saveOrUpdateBook(book);
		} catch (Exception e) {
			String errorPage = "【物资管理/图书/新增】保存或更新【图书】异常！" + e.toString();
			log.info(errorPage);
			request.setAttribute("errorPage", errorPage);
			request.setAttribute("position", "出错了");
			return mapping.findForward("errorPage");
		}

		request.setAttribute("pageNum", pageNum);
		listBookByPage(mapping, form, request, response);
		return mapping.findForward("listBook");
	}

}